<script lang="tsx">
import { useDesign } from '@/hooks/useDesign';
import { useAppStore } from '@/store/modules/app';
import { propTypes } from '@/utils/propTypes';
import { ElMenu, ElScrollbar } from 'element-plus';
import { storeToRefs } from 'pinia';
import { computed, defineComponent, unref } from 'vue';
import { useRouter } from 'vue-router';
import { useRenderMenuItem } from './components/useRenderMenuItem';

const prefixCls = useDesign().getPrefixCls('menu');

export default defineComponent({
  name: 'Menu',
  props: {
    menuSelect: propTypes.func.def(undefined)
  },
  setup(props) {
    const { push, currentRoute } = useRouter();
    const { layout, collapse, uniqueOpened } = storeToRefs(useAppStore());

    const menuMode = computed((): 'vertical' | 'horizontal' => {
      const vertical: LayoutType[] = ['classic', 'topLeft', 'cutMenu'];
      if (vertical.includes(unref(layout))) {
        return 'vertical';
      } else {
        return 'horizontal';
      }
    });

    const routers = computed(() => {
      return unref(layout) === 'cutMenu' ? [] : [];
    });

    const renderMenuWrap = () => {
      if (unref(layout) === 'top') {
        return renderMenu();
      } else {
        return <ElScrollbar>{renderMenu()}</ElScrollbar>;
      }
    };

    const renderMenu = () => {
      return (
        <ElMenu
          mode={unref(menuMode)}
          collapse={unref(layout) === 'top' || unref(layout) === 'cutMenu' ? false : unref(collapse)}
          uniqueOpened={unref(layout) === 'top' ? false : unref(uniqueOpened)}
          popperClass={unref(menuMode) === 'vertical' ? `${prefixCls}-popper--vertical` : `${prefixCls}-popper--horizontal`}
          onSelect={(index: string) => {
            props.menuSelect?.(index);
            push(index);
          }}
        >
          {{
            default: () => {
              const { renderMenuItem } = useRenderMenuItem(unref(menuMode));
              return renderMenuItem(unref(routers));
            }
          }}
        </ElMenu>
      );
    };

    return () => (
      <div
        id={prefixCls}
        class={[
          `${prefixCls} ${prefixCls}__${unref(layout)}`,
          'h-full overflow-hidden flex-col bg-[var(--left-menu-bg-color)]',
          {
            'w-[var(--left-menu-min-width)]': unref(collapse) && unref(layout) !== 'cutMenu',
            'w-[var(--left-menu-max-width)]': !unref(collapse) && unref(layout) === 'cutMenu'
          }
        ]}
      >
        {renderMenuWrap()}
      </div>
    );
  }
});
</script>
